/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proteoformer;

import java.io.File;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import uk.ac.ebi.pride.tools.mgf_parser.MgfFile;
import uk.ac.ebi.pride.tools.mgf_parser.model.Ms2Query;
import uk.ac.ebi.pride.tools.pride_spectra_clustering.SpectraClustering;
import uk.ac.ebi.pride.tools.pride_spectra_clustering.impl.FrankEtAlClustering;
import uk.ac.ebi.pride.tools.pride_spectra_clustering.util.ClusteringSpectrum;
import uk.ac.ebi.pride.tools.pride_spectra_clustering.util.SpectraCluster;


/**
 *
 * @author jonesar
 */
public class SpectralClustering {

    
    //String mgfFile = "C:/Work/ProteomicsSoftware/TopDown/ExampleData/SamPayne/peakPicked/SBEP_STM_004_02222012_Aragon_msdeconv_edit.mgf";
    //String mgfFile = "C:/Work/ProteomicsSoftware/TopDown/ExampleData/SamPayne/peakPicked/SBEP_STM_004_02222012_Aragon_msdeconv_edit_small.mgf";
     String mgfFile = "C:/Work/ProteomicsSoftware/TopDown/ExampleData/SamPayne/peakPicked/SBEP_STM_004_02222012_Aragon_msdeconv_edit_medium.mgf";
    double HMASS  = 1.00794;
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        SpectralClustering sc = new SpectralClustering();
        sc.processSpectra();
    }
    
    
    private void processSpectra(){
        
        try{
            File myFile = new File(mgfFile);
            MgfFile mgfFile = new MgfFile(myFile);

            // load all spectra into memory
            System.out.print("Loading spectra...");
            List<ClusteringSpectrum> spectra = loadSpectraFromFile(mgfFile);
            System.out.println("...done");
            
            // Initialize the clustering
            SpectraClustering clustering = new FrankEtAlClustering(); // this is an adapted implementation of the algorithm presented by Frank et al. in 2011

            // set the variables required for the clustering process
            // the settings used here are the same ones as the ones
            // used to cluster the PRIDE database
            //clustering.setClusteringRounds(4);
            //clustering.setSimilarityThreshold(0.7);
            
            clustering.setClusteringRounds(4);
            clustering.setSimilarityThreshold(0.2);
            
            System.out.print("Clustering...");
            List<SpectraCluster> createdCluster = clustering.clusterConvertedSpectra(spectra);
            System.out.println("...done");
            
            int i = 0;
            for (SpectraCluster cluster : createdCluster) {
                // the average precursor m/z of all spectra within the cluster
                double averageMZ = cluster.getAverageMz();
                //System.out.println("Cluster " + i + " average MZ:" + averageMZ);
                
                String clusterID = "Cluster" + i;

                // the list of spectra added to the cluster
                for (ClusteringSpectrum spectrum : cluster.getSpectra()) {
                    // ClusteringSpectrum also implements jmzReader's spectrum interface
                    double precMZ = spectrum.getPrecursorMZ();
                    double z = spectrum.getPrecursorCharge();
                    double precMass = (precMZ - (z * HMASS))/z;
                    String id = spectrum.getId();
                    
                    System.out.println(clusterID+"\t" + id + "\t" + precMass);
                }
                i++;
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    
    
    private static List<ClusteringSpectrum> loadSpectraFromFile(MgfFile mgfFile) throws Exception {
        List<ClusteringSpectrum> spectra = new ArrayList<ClusteringSpectrum>(mgfFile.getMs2QueryCount());

        Iterator<Ms2Query> it = mgfFile.getMs2QueryIterator();
        Set<String> processedIds = new HashSet<String>();

        while(it.hasNext()) {
            Ms2Query query = it.next();

            // make sure every spectrum is only used once
            if (processedIds.contains(query.getTitle()))
                continue;

            processedIds.add(query.getTitle());

            // set the intensity to 1 in case it's missing
            if (query.getPeptideIntensity() == null)
                query.setPeptideIntensity(1.0);


            // throw an exception in case it's missing
            if (query.getPrecursorCharge() == null) {
                throw new Exception("Spectrum is missing precursor charge.");
            }



            // change the id to title
        // ClusteringSpectrum spectrum = new ClusteringSpectrum(query.getTitle(),query.getPrecursorMZ(),query.getPrecursorIntensity(),query.getPrecursorCharge(),query.getPeakList(),null,query.getMsLevel());

            double dummyPrecursorIntensity = 1.0;
            int msLevel =2;

            if(query.getPeakList() != null){

                ClusteringSpectrum spectrum = new ClusteringSpectrum(query.getTitle(),query.getPrecursorMZ(),dummyPrecursorIntensity,query.getPrecursorCharge(),query.getPeakList(),null, msLevel);

                spectra.add(spectrum);

            }
        }

        return spectra;
        }
    
}
